package com.shouhuobao.bhi.receiver;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.collectplus.express.R;
import com.collectplus.express.logic.AppCache;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.DialogMgr;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.model.ReceiverBean;
import com.collectplus.express.model.SenderBean;

import java.util.ArrayList;

import droid.frame.activity.HandlerMgr;
import droid.frame.app.Callback;

/**
 * 收件人历史
 *
 * @author coffee<br>
 * 2015-6-17下午5:18:52
 */
public class ReceiverHistoryFragment extends ReceiverAddBaseFragment implements OnClickListener {

    private ListView mListView;
    private ReceiverHistoryAdapter mAdapter;

    private int mPageNum = 1;
    /**
     * 不支持的地区
     */
    private String regex = "(新疆|西藏|海南|青海|贵州)+.*?";

    /**
     * 选中的联系人Id,
     */
    private StringBuilder selectIds = new StringBuilder();
    // private DeletePopupWindow mDdeletePopwin;// 删除框
    private int position;// 当前操作(长按)的item

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        showLoadingDialog(null);
        //addType:地址类型1：收件，2：寄件
        AppHttp.getInstance().senderList(mPageNum, 1);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.receiver_history);
        super.findViewById();
        mListView = (ListView) findViewById(R.id.listview);
        mListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ReceiverBean item = (ReceiverBean) parent.getItemAtPosition(position);
                //
                //				if (item.getProvince().matches(regex)) {
                //					showToast("抱歉, 暂不能寄往" + item.getProvince() + "地区");
                //				} else {
                onCheck(item);
                mAdapter.setCheck(position);
                //				}
            }
        });
        //        mListView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
        //            @Override
        //            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        //                menu.add(0, 1, 0, "删除收件人");
        //                // menu.add(0, 2, 0, "编辑收件人");
        //            }
        //        });
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(final AdapterView<?> parent, View view, final int position, long id) {
                ReceiverHistoryFragment.this.position = position;
                //                mListView.showContextMenu();
                final ReceiverBean receiver = mAdapter.getItem(position);
                DialogMgr.deleteReceiverHistory(getActivityContext(), receiver, new Callback() {
                    @Override
                    public void onDialogDismiss() {
                        showLoadingDialog(null);
                        AppHttp.getInstance().receiverDeleteFromHistory(receiver.getId(), position);
                    }
                });
                return true;
            }
        });
    }

    //    @Override
    //    public boolean onContextItemSelected(MenuItem item) {
    //        switch (item.getItemId()) {
    //            case 1:// 删除
    //                ReceiverBean receiver = mAdapter.getItem(position);
    //                showLoadingDialog(null);
    //                AppHttp.getInstance().receiverDeleteFromHistory(receiver.getId(), position);
    //                break;
    //            case 2:// 编辑收件人
    //                Intent intent = new Intent();
    //                intent.setClass(getActivityContext(), ReceiverEditActivity.class);
    //                receiver = mAdapter.getItem(position);
    //                intent.putExtra("item", receiver);
    //                intent.putExtra("from", "history");
    //                startActivityForResult(intent, 100);
    //                break;
    //        }
    //        return super.onContextItemSelected(item);
    //    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.receiver_edit:
                ReceiverBean item = (ReceiverBean) v.getTag();
                //                if (item.getProvince().matches(regex)) {
                //                    showToast("抱歉, 暂不能寄往" + item.getProvince() + "地区");
                //                } else {
                HandlerMgr.sendMessage(MsgID.receiver_edit_history2new, item);
                //                }
                break;
        }
    }

    private void onCheck(ReceiverBean item) {
        selectIds.setLength(0);
        selectIds.append(item.getId());// 收件人ID
        selectIds.append(",");
        if (TextUtils.isEmpty(selectIds.toString())) {
            showToast("请选择联系人");
            return;
        }
        ReceiverBean cacheReceiver = AppCache.getParcelNew();
        boolean isReceiver = ((ReceiverTabFragmentActivity) getActivityContext()).isReceiver();
        if (isReceiver == false) {// 添加寄件人
            SenderBean sender = new SenderBean();
            sender.setId(item.getId());
            sender.setName(item.getName());
            sender.setPhone(item.getPhone());
            sender.setProvince(item.getProvince());
            sender.setCity(item.getCity());
            sender.setDistrict(item.getDistrict());
            sender.setAddress(item.getAddress());
            cacheReceiver.setSender(sender);
            //
            Intent data = new Intent();
            getActivityContext().setResult(Activity.RESULT_OK, data);
            getActivityContext().finish();
        } else {// 收件人
            // 标准寄件
//            if (cacheReceiver.isGoHomeStandard()) {
//                Intent intent = new Intent();
//                intent.setClass(getActivityContext(), ExpressCompanyActivity.class);
//                intent.putExtra("item", item);
//                startActivityForResult(intent, 1004);
//            } else {
            cacheReceiver.copyReceiver(item);
            cacheReceiver.copyRegion(item);
            //
            Intent data = new Intent();
            getActivityContext().setResult(Activity.RESULT_OK, data);
            getActivityContext().finish();
//            }
        }
    }

    public boolean handleMessage(final Message msg) {
        switch (msg.what) {
            // 获取最新联系人
            case MsgID.senderList:
                cancelLoadingDialog();
                final AppResult<ReceiverBean> appResult = JSON.parseList(msg.obj, ReceiverBean.class);
                //
                if (appResult.isSuccess()) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mAdapter = new ReceiverHistoryAdapter(getActivityContext(), appResult.getResultList(), ReceiverHistoryFragment.this);
                            mListView.setAdapter(mAdapter);
                        }
                    });
                }
                return true;
            // 删除历史收件人
            case MsgID.receiver_Delete_from_history:
                cancelLoadingDialog();
                final AppResult<?> deleteResult = JSON.parser(msg.obj);

                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        if (deleteResult.isSuccess()) {
                            int removedPosition = msg.arg1;

                            // 如果删除的是已经选中的(注意msg.arg1 即可能是List的下标 也可能是list的元素)
                            if (mAdapter.getSelectItems().contains(msg.arg1)) {
                                mAdapter.getSelectItems().remove(Integer.valueOf(removedPosition));
                            }
                            ArrayList<Integer> tmps = new ArrayList<Integer>();
                            for (Integer position : mAdapter.getSelectItems()) {
                                if (position < removedPosition) {
                                    tmps.add(position);
                                } else if (position > removedPosition) {
                                    tmps.add(position - 1);
                                } else {
                                    // 删除的是选中的
                                    continue;
                                }
                            }
                            mAdapter.getSelectItems().clear();
                            mAdapter.getSelectItems().addAll(tmps);
                            mAdapter.getItems().remove(removedPosition);
                            mAdapter.notifyDataSetChanged();
                        } else {
                            showToast(deleteResult.getMessage());
                        }

                    }
                });
                return true;
        }
        return super.handleMessage(msg);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
            ReceiverBean receiver = (ReceiverBean) data.getSerializableExtra("item");
            mAdapter.getItems().remove(position);
            mAdapter.getItems().add(position, receiver);
            mAdapter.notifyDataSetChanged();
        }
        // 选择快递公司--回调
        else if (requestCode == 1004 && resultCode == Activity.RESULT_OK) {
            ReceiverBean cacheReceiver = AppCache.getParcelNew();
            ReceiverBean item = mAdapter.getItem(mAdapter.getSelectItems().get(0));
            cacheReceiver.copyReceiver(item);
            cacheReceiver.copyRegion(item);
            //
            String expressCompanyId = data.getStringExtra("companyId");
            String expressCompanyName = data.getStringExtra("expressCompanyName");
            String totalPrice = data.getStringExtra("totalPrice");
            String weight = data.getStringExtra("weight");
            // update cache
            cacheReceiver.setExpressCompanyId(expressCompanyId);
            cacheReceiver.setExpressCompanyName(expressCompanyName);
            cacheReceiver.setExpressPrice(totalPrice);
            cacheReceiver.setWeight(weight);
        }
    }
}
